package gridModel;

import globalTools.Languages;

import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import appModel.StdSaveData;

public class StdPlayableGridModel extends StdGridModel implements PlayableGridModel {
	
	class Timer extends Thread {
		static final long INTERVAL = 1000; // Echelons de 1 seconde
		static final long MAX_TIME = 100000000; // 10000 secondes ~ 2h45
		final PropertyChangeSupport timerListeners;
		public Timer() {
			super();
			timerListeners = new PropertyChangeSupport(this);
		}
		public void run() {
			while (!allFinished() && timerOn && time < MAX_TIME) {
				try {
					Thread.sleep(INTERVAL);
					long oldTime = time;
					time += INTERVAL;
					listeners.firePropertyChange("time", oldTime / 1000, time / 1000);
				} catch (InterruptedException e) {
					// Rien
				}
			}
		}
	}
	
	// ATTRIBUTS
	
	private static final long serialVersionUID = 1L;
	
	private final Map<NamedColor, PixGrid> solutionGrids;
	private volatile long time;
	private volatile boolean timerOn;
	
	// CONSTRUCTEUR
	
	public StdPlayableGridModel(EditableGridModel m) {
		super(new HashMap<Languages, String>(m.getNames()));
		file = m.getFileName();
		solutionGrids = new HashMap<NamedColor, PixGrid>(m.getGrid());
		playableGrids = new HashMap<NamedColor, PixGrid>();
		for (NamedColor c : solutionGrids.keySet()) {
			if (actualColor == null) {
				actualColor = c;
			}
			playableGrids.put(c, new StdPixGrid(solutionGrids.get(c).getWidth(), solutionGrids.get(c).getHeight(), true));
		}
	}
	
	// REQUETES

	@Override
	public boolean allFinished() {
		return solutionGrids.equals(playableGrids);
	}
	
	@Override
	public boolean isComplete(NamedColor c) {
		return playableGrids.get(c).equals(solutionGrids.get(c));
	}
	
	@Override
	public List<List<Integer>> getHorizontalIndex(NamedColor c) {
		return solutionGrids.get(c).getHorizontalIndex();
	}
	
	@Override
	public List<List<Integer>> getVerticalIndex(NamedColor c) {
		return solutionGrids.get(c).getVerticalIndex();
	}
	
	@Override
	public long getTime() {
		return time;
	}
	
	@Override
	public boolean timerOn() {
		return timerOn;
	}
	
	// COMMANDES
	
	@Override
	public void startTimer() {
		timerOn = true;
		(new Timer()).start();
	}
	
	@Override
	public void save() throws IOException {
		timerOn = false;
		StdSaveData.getSavedData().saveGame(this);
	}

}
